package Servlet;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

@WebServlet(name = "RegisterServlet", urlPatterns = "/registerServlet")
public class RegisterServlet extends HttpServlet {

    @Override
    public void init(ServletConfig config) throws ServletException {

        super.init(config);

        try {
            System.setOut(new PrintStream(System.out,true,"UTF-8"));
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
        System.out.println("开始读取上下文参数信息");
        ServletContext servletContext = getServletContext();
        Enumeration<String> initParameterNames = servletContext.getInitParameterNames();
        while(initParameterNames.hasMoreElements()){
            String initParameterName = initParameterNames.nextElement();
            String initParameterValue = servletContext.getInitParameter(initParameterName);
            System.out.println(initParameterName + "=>" + initParameterValue);
        }
        System.out.println("结束读取上下文参数信息");
        System.out.println("============");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.setOut(new PrintStream(System.out,true,"UTF-8"));
        System.out.println("开始获取请求头信息");
        Enumeration<String> headerNames = req.getHeaderNames();
        while(headerNames.hasMoreElements()){
            String headerName = headerNames.nextElement();
            String headerValue = req.getHeader(headerName);
            System.out.println(headerName + "=>" + headerValue);
        }
        System.out.println("结束获取请求头信息");
        System.out.println("============");

        System.out.println("请求方式："+req.getMethod());
        System.out.println("请求地址："+req.getRequestURI());
        System.out.println("请求的上下文路径"+req.getContextPath());
        System.out.println("============");

        System.out.println("开始获取请求参数信息");
        Map<String,String[]> parameterMap = req.getParameterMap();
        parameterMap.forEach((k,v)-> System.out.println(k+"=>"+ Arrays.toString(v)));
        System.out.println("结束获取请求参数信息");
        System.out.println("============");

        System.out.println("response响应开始");
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=utf-8");
        PrintWriter writer = resp.getWriter();
        writer.print("注册请求已处理");
        writer.flush();
        writer.close();
    }
}
